package com.wman.sheep.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/2/14.
 */

public class GsonTool {
    /**
     * 序列化时，null列不处理问题，添加serializeNulls()。
     */
    private static Gson gson = new GsonBuilder().serializeNulls().create();

    public static String toJson(Object data) {
        return gson.toJson(data);
    }

    /**
     * 反序列化时
     * 1、int 转变为 double 问题，重写map适配器，判断number逻辑
     *
     * @return
     */
    //调用：List<Map<String,Object>> jsonList = GsonUtil.fromJson(json,new TypeToken<List<Map<String,Object>>>(){});
    public static <T> T fromJson(String json, TypeToken<T> typeToken) {
        Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(new TypeToken<Map<String, Object>>() {
                }.getType()
                , new MapTypeAdapter()).create();
        return gson.fromJson(json, typeToken.getType());
    }


    /**
     * 推荐方法 gson解析集合
     *
     * @param jsonData
     * @param clazz
     * @return
     */
    public static <T> List<T> parseListFromJson(String jsonData, Class<T> clazz) {
        Type listType = new TypeToken<ArrayList<T>>() {
        }.getType();
        //        Gson gson = new Gson();
        Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(listType, new MapTypeAdapter()).create();
        List<T> tList = gson.fromJson(jsonData, listType);
        return tList;
    }

    public static <T> List<T> parseListFromJson(Object jsonData, Class<T> clazz) {
        Type listType = new TypeToken<List<T>>() {
        }.getType();
        //        Gson gson = new Gson();
        Gson gson = new GsonBuilder().serializeNulls().registerTypeAdapter(listType, new MapTypeAdapter()).create();
        List<T> tList = gson.fromJson(gson.toJson(jsonData), listType);

        return tList;
    }

    public static <T> T parseOneFromJson(Object jsonData, Class<T> clazz) {
        Gson gson = new Gson();

        T user = gson.fromJson(gson.toJson(jsonData), clazz);

        return user;
    }

    public static <T> T parseOneFromJson(String jsonData, Class<T> clazz) {
        Gson gson = new Gson();

        T user = gson.fromJson(jsonData, clazz);

        return user;
    }

    public static class MapTypeAdapter extends TypeAdapter<Object> {
        @Override
        public Object read(JsonReader in) throws IOException {
            JsonToken token = in.peek();
            switch (token) {
                case BEGIN_ARRAY:
                    List<Object> list = new ArrayList<>();
                    in.beginArray();
                    while (in.hasNext()) {
                        list.add(read(in));
                    }
                    in.endArray();
                    return list;

                case BEGIN_OBJECT:
                    Map<String, Object> map = new LinkedTreeMap<>();
                    in.beginObject();
                    while (in.hasNext()) {
                        map.put(in.nextName(), read(in));
                    }
                    in.endObject();
                    return map;

                case STRING:
                    return in.nextString();

                case NUMBER:
                    /**
                     * 改写数字的处理逻辑，将数字值分为整型与浮点型。
                     */
                    double dbNum = in.nextDouble();

                    // 数字超过long的最大值，返回浮点类型
                    if (dbNum > Long.MAX_VALUE) {
                        return dbNum;
                    }

                    // 判断数字是否为整数值
                    long lngNum = (long) dbNum;
                    if (dbNum == lngNum) {
                        return lngNum;
                    } else {
                        return dbNum;
                    }

                case BOOLEAN:
                    return in.nextBoolean();

                case NULL:
                    in.nextNull();
                    return null;

                default:
                    throw new IllegalStateException();
            }
        }

        @Override
        public void write(JsonWriter out, Object value) throws IOException {
            // 序列化无需实现
        }
    }
}
